package com.lenovo.agent.proxy;


import com.alibaba.fastjson.JSONObject;
import com.lenovo.agent.enums.CodeEnum;
import com.lenovo.agent.proxy.request.GptRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @Author: leiwk2
 * @Date: 2024/10/17 17:17
 */
@Component
@Slf4j
public abstract class GptProxy<T> extends HttpProxy {

    public static final String ERROR_REPLY = "抱歉，我没有理解您的意思，请重新输入";

    public T genChat(String text) {
        if (openMock()) {
            return mockResponse();
        }
        GptRequest model = new GptRequest();
        model.setPrompt(text);
        String response;
        try {
            response = postBody(gptUrl(), model);
        } catch (Exception e) {
            log.error("genChat postBody error", e);
            throw new RuntimeException("抱歉，服务器忙碌，请稍后再试");
        }
        checkResponse(response);

        return parseResponse(response);
    }

    protected abstract boolean openMock();

    protected abstract String gptUrl();

    protected abstract T mockResponse();

    protected abstract T parseResponse(String response);

    protected void checkResponse(String response) {
        if (StringUtils.isBlank(response)) {
            log.error("reply is blank");
            throw new RuntimeException(ERROR_REPLY);
        }

        JSONObject replyJson;
        try {
            replyJson = JSONObject.parseObject(response, JSONObject.class);
        } catch (Exception e) {
            log.error("parseReply error", e);
            throw new RuntimeException(ERROR_REPLY);
        }

        Integer code = replyJson.getInteger("code");
        if (!CodeEnum.SUCCESS.getCode().equals(code)) {
            throw new RuntimeException(ERROR_REPLY);
        }
    }
}
    

    